//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by NeXTSTEP on 15/9/29.
//  Copyright © 2015年 NeXTSTEP. All rights reserved.
//

import UIKit
import AFNetworking

let WBSwitchToRootVC = "WBSwitchToRootVC"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()

        setNetwork()
        setThemeColor()
        //添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "SwitchToRootVC:", name: WBSwitchToRootVC, object: nil)
        
        showMainInterFace()
        
        return true
    }
    
    private func showMainInterFace(){
        var sbName = "Main"
        if UserAccount.shareUserAccount != nil {
            sbName = isNeedUpdate() ? "NewFeature" : "WelCome"
        }
        let sb = UIStoryboard(name: sbName, bundle: nil)
        let VC = sb.instantiateInitialViewController()
        window?.rootViewController = VC
    }

    //设置全局外观
    private func setThemeColor(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    private func setNetwork(){
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        let cache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(cache)
    }
    
    func SwitchToRootVC(notification: NSNotification){
        print(notification)
        let sbName = notification.object as! String
        let sb = UIStoryboard(name: sbName, bundle: nil)
        let VC = sb.instantiateInitialViewController()
        window?.rootViewController = VC
    }
    
    
    func isNeedUpdate() -> Bool {
        let dict = NSBundle.mainBundle().infoDictionary!
        let currentVersion = dict["CFBundleShortVersionString"] as! NSString
        let versionNum = currentVersion.doubleValue
        
        // 获取沙盒版本
        let sandBoxKey = "update"
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let sandBoxVersion = userDefaults.doubleForKey(sandBoxKey)
        
        //将当前版本存储到沙盒
        userDefaults.setDouble(versionNum, forKey: sandBoxKey)
        userDefaults.synchronize()
        return versionNum > sandBoxVersion
    }

}

